#include "cpu/exec/helper.h"

#define DATA_BYTE 1
#include "push-template.h"
#undef DATA_BYTE

#define DATA_BYTE 2
#include "push-template.h"
#undef DATA_BYTE

#define DATA_BYTE 4
#include "push-template.h"
#undef DATA_BYTE

make_helper_v(push_r)
make_helper_v(push_i)
make_helper_v(push_rm)
make_helper(pushA_w){
    uint16_t temp_sp = cpu.esp;
    
    // 注意：压入的顺序是固定的
    cpu.esp -= 2; swaddr_write(cpu.esp, reg_w(R_DI), 2);
    cpu.esp -= 2; swaddr_write(cpu.esp, reg_w(R_SI), 2);
    cpu.esp -= 2; swaddr_write(cpu.esp, reg_w(R_BP), 2);
    cpu.esp -= 2; swaddr_write(cpu.esp, temp_sp, 2);  // 压入原始SP值
    cpu.esp -= 2; swaddr_write(cpu.esp, reg_w(R_BX), 2);
    cpu.esp -= 2; swaddr_write(cpu.esp, reg_w(R_DX), 2);
    cpu.esp -= 2; swaddr_write(cpu.esp, reg_w(R_CX), 2);
    cpu.esp -= 2; swaddr_write(cpu.esp, reg_w(R_AX), 2);
    
    print_asm("pusha");
    return 1;
}
make_helper(pushA_l){
    uint32_t temp_esp = cpu.esp;
    
    cpu.esp -= 4; swaddr_write(cpu.esp, reg_l(R_EDI), 4);
    cpu.esp -= 4; swaddr_write(cpu.esp, reg_l(R_ESI), 4);
    cpu.esp -= 4; swaddr_write(cpu.esp, reg_l(R_EBP), 4);
    cpu.esp -= 4; swaddr_write(cpu.esp, temp_esp, 4);  // 压入原始ESP值
    cpu.esp -= 4; swaddr_write(cpu.esp, reg_l(R_EBX), 4);
    cpu.esp -= 4; swaddr_write(cpu.esp, reg_l(R_EDX), 4);
    cpu.esp -= 4; swaddr_write(cpu.esp, reg_l(R_ECX), 4);
    cpu.esp -= 4; swaddr_write(cpu.esp, reg_l(R_EAX), 4);
    
    print_asm("pushad");
    return 1;
}
make_helper_v(pushA)
// PUSHF - 16位模式：压入FLAGS低16位
make_helper(pushf_w) {
    cpu.esp -= 2;
    swaddr_write(cpu.esp, cpu.eflags.val & 0xFFFF, 2);  // 只压入低16位
    
    print_asm("pushf");
    return 1;
}

// PUSHFD - 32位模式：压入完整EFLAGS
make_helper(pushf_l) {
    cpu.esp -= 4;
    swaddr_write(cpu.esp, cpu.eflags.val, 4);  // 压入完整32位EFLAGS
    
    print_asm("pushfd");
    return 1;
}
make_helper_v(pushf)